// src/services/api.js
import axios from 'axios'
import { notification, Modal } from 'antd'
class ApiService {
    private axiosInstance: import('axios').AxiosInstance

    constructor() {
        const baseURL = import.meta.env.VITE_API_BASE_URL
        this.axiosInstance = axios.create({
            baseURL,
            timeout: 10000,
            withCredentials: true,
        })
        this.setupInterceptors()
    }
    setupInterceptors() {
        // 请求拦截器
        this.axiosInstance.interceptors.request.use(
            (config: import('axios').InternalAxiosRequestConfig) => {
                // 如果有 X-Skip-Auth，则跳过 token 注入
                if (config.headers && config.headers['X-Skip-Auth']) {
                    return config
                }
                const token = this.getToken()
                if (token) {
                    config.headers = config.headers || {}
                    config.headers.Authorization = `Bearer ${token}`
                }
                return config
            },
            (error) => Promise.reject(error)
        )

        // 响应拦截器
        this.axiosInstance.interceptors.response.use(
            (response) => {
                // console.log('Response Status:', response) // 添加日志输出
                // 如果请求带有 X-Skip-Auth，则不弹窗提示
                if (
                    response.config.headers &&
                    response.config.headers['X-Skip-Auth']
                ) {
                    return response.data
                }
                if (response.data && response.data.status !== 200) {
                    const config = {
                        message: '请求失败',
                        description:
                            response.data.message || response.data.msg || '请求失败，请重试',
                        duration: 2,
                    }
                    notification.error(config)
                }
                // console.log('Response Data:', response.data) // 添加日志输出
                return response.data
            },
            (error) => {
                this.handleError(error)
                return Promise.reject(error)
            }
        )
    }

    getToken() {
        return localStorage.getItem('authToken')
    }

    handleError(error: any) {
        console.error('API Error:', error)
        if (error.response?.status === 401) {
            Modal.confirm({
                title: '登录过期',
                content: '您的登录状态已过期，请重新登录以继续使用。',
                okText: '确定',
                cancelText: '取消',
                onOk: () => {
                    // 这里添加退出登录的逻辑
                    this.handleUnauthorized()
                    // 重定向跳转到登录页
                    window.location.href = '/login'
                },
            })
        }
        if (error.response.status === 400) {
            const config = {
                message: '登录失败',
                description: error?.response?.data?.msg || '登录失败，请重试',
                duration: 2,
            }
            notification.error(config)
        }
        // 500
        if (error.response.status === 500) {
            const config = {
                message: '服务器错误',
                description:
                    error?.response?.data?.msg || '服务器发生错误，请稍后重试',
                duration: 2,
            }
            notification.error(config)
        } else {
            const config = {
                message: '请求失败',
                description:
                    error?.response?.data?.message || error?.response?.data?.msg || '请求失败，请重试',
                duration: 2,
            }
            notification.error(config)
        }
        // 其他错误处理...
    }

    handleUnauthorized() {
        localStorage.removeItem('authToken')
        // window.location.href = '/login'
    }

    // 封装常用方法
    get(url: string, params = {}, config = {}) {
        return this.axiosInstance.get(url, { params, ...config })
    }

    post(url: string, data = {}, config = {}) {
        return this.axiosInstance.post(url, data, config)
    }

    put(url: string, data = {}) {
        return this.axiosInstance.put(url, data)
    }

    delete(url: string) {
        return this.axiosInstance.delete(url)
    }
}

export default new ApiService()
